<template>
  <el-dialog
          :model-value="visible"
          :title="sourceFiletype == 'image' ? '导入云存储图片' : '导入云存储视频'"
          :before-close="cancelFolderDialog"
          width="60%"
          top="5vh"
  >
    <el-row align="middle">
      <el-col :span="18">
        <el-breadcrumb class="app-breadcrumb" separator="/">
          <transition-group name="breadcrumb">
            <el-breadcrumb-item v-for="(item,index) in breadcrumbList" :key="index">
              <span v-if="index==breadcrumbList.length-1" class="no-redirect">{{ item.name }}</span>
              <a v-else @click.prevent="handlerLink(item)">{{ item.name }}</a>
            </el-breadcrumb-item>
          </transition-group>
        </el-breadcrumb>
      </el-col>
      <el-col :span="6" v-if="!isRoot && sourceFiletype == 'image'">
        <div align="right">
         <!-- <el-button type="primary" size="mini" @click="handleUploadFile">
            <el-icon>
              <upload-filled />
            </el-icon>
            上传图片
          </el-button>-->
          <el-upload
                  :action="uploadAction"
                  multiple
                  name="upfile"
                  :data="uploadFormData"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :with-credentials="true"
          >
            <el-button type="primary" size="mini">
              <el-icon>
                <upload-filled />
              </el-icon>
              上传图片
            </el-button>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="24" class="mt10">
        <el-table
                ref="folderTableRef"
                :data="tableData.dataList"
                border
                v-loading="isloading"
                max-height="400px"
                @select="handlerSelect"
                @select-all="handlerSelectAll"
                @row-click="handleClickRowSelect"
        >
          <el-table-column type="selection" width="50" :selectable="selectable" align="center" />
          <el-table-column label="文件名称" :show-overflow-tooltip="true">
            <template #default="{row}">
              <a @click.prevent="handlerLink(row)" v-if="row.filetype == 0" href="" class="flex align-items">
                <el-icon>
                  <folder />
                </el-icon>
                <span class="txttdellipsis">{{row.name}}</span>
              </a>
              <span v-else-if="row.filetype == 2" class="flex align-items">
                <span @click.stop>
                  <el-image
                          :preview-src-list="srcList"
                          :initial-index="initialIndex(row.fid)"
                          :src="getStorageImageUrl(row.fid, 2)"
                  />
                </span>
                <span class="txttdellipsis">{{row.name}}</span>
              </span>
                <a v-else-if="row.filetype == 7" class="flex align-items" href="javascript:;" @click.stop="handleVideoPlay(row)">
                  <el-icon>
                    <video-play />
                  </el-icon>
                  <span class="txttdellipsis">{{row.name}}</span>
                </a>
              <audio-table-column
                v-else-if="row.filetype == 4"
                :ref="el => { if (el) audioTableColumnRef[row.fid] = el }"
                :row="row"
                sourcefrom="storage"
                @handleAudioPlay="handleAudioPlay"
              />
                <span class="flex align-items" v-else>
                  <el-icon>
                    <document />
                  </el-icon>
                  <span class="txttdellipsis">{{row.name}}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="FID" :show-overflow-tooltip="true" align="center">
            <template #default="{row}">
              <span v-if="row.fid" class="txttdellipsis">{{row.fid}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" width="100" align="center">
            <template #default="{row}">
              <span v-if="row.fsize > 0">{{formatSize(row.fsize)}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="ctime" />
        </el-table>
      </el-col>
      <el-col :span="24" class="mt10">
        <folder-pagination
                v-if="!isRoot"
                :queryList="queryList"
                :total="tableData.total"
                @pagination="getDataList"
        />
      </el-col>
    </el-row>
    <upload-file
            ref="uploadFileRef"
            :dialog-upload-path="dialogUploadPath"
            :dialog-upload-title="dialogUploadTitle"
            :dialog-upload-visible="dialogUploadVisible"
            @handleCancelUploadDialog="handleCancelUploadDialog"
            @reloadFileList="getDataList"
    />
    <template #footer>
      <div align="center" v-if="!isRoot">
        <el-button type="default" size="small" @click="cancelFolderDialog">取消</el-button>
        <el-button type="primary" size="small" @click="handleConfirm">确定导入</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import {ref, toRef, reactive, onUpdated, nextTick, computed} from 'vue'
  import { Folder,
    Document,
    VideoPlay,
    UploadFilled
  } from "@element-plus/icons"
  import {getFolder} from "@/api/media/storage";
  import {getStorageImageUrl} from "@/utils/usage-config";
  import FolderPagination from "./components/FolderPagination";
  import {formatSize, mimeTypeList} from "@/utils/usage-config";
  import {exportStorageImage, getExportStorageImage} from "@/api/media/image";
  import {ElMessage} from 'element-plus'
  import {exportStorageVideo, getExportStoragevideo} from "@/api/media/video";
  import UploadFile from "./components/UploadFile";
  import AudioTableColumn from "@/components/Common/AudioTableColumn";

  export default {
    name: "rootFolder",
    components: {UploadFile, Folder, Document, VideoPlay, FolderPagination, UploadFilled, AudioTableColumn},
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rootFolderList: {
        type: Array,
        default() {
          return []
        }
      },
      filetype: {
        type: String,
        default: 'image'
      }
    },
    emits: ['cancelFolderDialog', 'getDataList', 'handleVideoPlay'],
    setup(props, context) {
      const rootFolderDataList = toRef(props, 'rootFolderList')
      const sourceFiletype = toRef(props, 'filetype')
      const queryList = reactive({
        path: '/',
        action: 'getlist',
        startnum: 1,
        pagenum: 25,
        type: 5,
        order: 2
      })
      const breadcrumbList = ref([
        {
          pid: 0,
          path: '/',
          name: '根目录'
        }
      ])
      const tableData = reactive({
        total: 0,
        dataList: []
      })
      const isloading = ref(false)
      const isRoot = ref(true)
      const srcList = ref([])
      const formData = reactive({
        groupid: undefined,
        img_list: [],
        video_list: [],
        data_list: [],
        list: [],
        checked_list: []
      })
      const folderTableRef = ref(null)
      const uploadAction = ref(process.env.VUE_APP_BASE_MEDIA_API + '/console/cloudstorage/image/upload')
      const uploadFormData = reactive({
        path: '/'
      })
      /** 文件上传相关参数开始 **/
      const dialogUploadVisible = ref(false)
      const dialogUploadTitle = ref('')
      const dialogUploadPath = ref('')
      const uploadFileRef = ref(null)
      /** 文件上传相关参数结束 **/

      const initialIndex = computed(() => {
        return (fid) => {
          const index = srcList.value.findIndex(src => {
            return src.indexOf(fid) != -1
          })
          return index
        }
      })

      onUpdated(() => {
        tableData.dataList = rootFolderDataList.value
      })
      const getDataList = () => {
        resetFormData()
        isloading.value = true
        getFolder(queryList).then(async(response) => {
          isloading.value = false
          tableData.total = response.totalnum
          tableData.dataList = response.data
          tableData.dataList.forEach(item => {
            if (sourceFiletype.value == 'image' && item.filetype == 2) {
              formData.list.push({
                groupid: formData.groupid,
                sourceid: item.fid
              })
            } else if(sourceFiletype.value == 'video' && (item.filetype == 7 || item.filetype == 4)) {
              formData.list.push({
                groupid: formData.groupid,
                sourceid: item.fid
              })
            }
          })
          if (formData.list.length > 0) {
            if (sourceFiletype.value == 'image') {
              await getExportStorageImage({data_list: formData.list}).then(res => {
                formData.checked_list = res.data
              })
            } else {
              await getExportStoragevideo({data_list: formData.list}).then(res => {
                formData.checked_list = res.data
              })
            }
          }
          srcList.value = []
          nextTick(() => {
            tableData.dataList.forEach(file => {
              const index = formData.checked_list.findIndex(item => {
                return item.groupid == formData.groupid && item.sourceid == file.fid && item.checked
              })
              if (index !== -1) {
                folderTableRef.value.toggleRowSelection(file, true)
              }
              if (file.filetype !== undefined && file.filetype == 2) {
                srcList.value.push(getStorageImageUrl(file.fid, 1))
              }
            })
          })
        })
      }
      const handlerLink = (item) => {
        if (item.groupid !== undefined) {
          formData.groupid = parseInt(item.groupid)
        }
        setBreadcrumb(item)
        uploadFormData.path = getBreadcrumbPath()
        queryList.startnum = 1
        queryList.path = getBreadcrumbPath()
        isRoot.value = breadcrumbList.value.length == 1
        if (isRoot.value) {
          resetFormData()
          tableData.dataList = rootFolderDataList.value
        } else {
          getDataList()
        }
      }
      const setBreadcrumb = (item) => {
        const index = breadcrumbList.value.findIndex(b => b.pid === item.pid)
        const pathTotal = breadcrumbList.value.length
        if (index === -1) {
          breadcrumbList.value.push({
            pid: item.pid,
            path: item.name,
            name: item.name
          })
        } else {
          breadcrumbList.value.splice(index+1, (pathTotal-index+1))
        }
      }
      const getBreadcrumbPath = () => {
        let pathArr = []
        breadcrumbList.value.forEach(b => {
          pathArr.push(b.path)
        })
        return pathArr.join('/')
      }
      const selectable = (row) => {
        const index = formData.checked_list.findIndex(item => {
          return item.groupid == formData.groupid && item.sourceid == row.fid && item.checked
        })
        if (index !== -1) {
          return  false
        }
        if (sourceFiletype.value == 'image') {
          if (row.filetype == 2) {
            return true
          } else {
            return false
          }
        } else {
          if (row.filetype == 7 || row.filetype == 4) {
            return true
          } else {
            return false
          }
        }
      }
      const cancelFolderDialog = () => {
        resetSourceData()
        context.emit('cancelFolderDialog')
      }
      const resetFormData = () => {
        formData.video_list = []
        formData.img_list = []
        formData.data_list = []
        formData.list = []
        formData.checked_list = []
      }
      const handlerSelect = (selection, row) => {
        if (row.filetype == 2) {
          const index = formData.img_list.findIndex(item => item.fid === row.fid)
          if (index === -1) {
            formData.img_list.push(row)
          } else {
            formData.img_list.splice(index, 1)
          }
        } else if (row.filetype == 7 || row.filetype == 4) {
          const index = formData.video_list.findIndex(item => item.fid === row.fid)
          if (index === -1) {
            formData.video_list.push(row)
          } else {
            formData.video_list.splice(index, 1)
          }
        }
      }
      const handleClickRowSelect = (row) => {
        if (row.filetype == 2) {
          if (sourceFiletype.value == 'image') {
            const index = formData.img_list.findIndex(item => item.fid === row.fid)
            if (index === -1) {
              folderTableRef.value.toggleRowSelection(row, true)
              formData.img_list.push(row)
            } else {
              folderTableRef.value.toggleRowSelection(row, false)
              formData.img_list.splice(index, 1)
            }
          }
        } else if (row.filetype == 7 || row.filetype == 4) {
          if (sourceFiletype.value == 'video') {
            const index = formData.video_list.findIndex(item => item.fid === row.fid)
            if (index === -1) {
              folderTableRef.value.toggleRowSelection(row, true)
              formData.video_list.push(row)
            } else {
              folderTableRef.value.toggleRowSelection(row, false)
              formData.video_list.splice(index, 1)
            }
          }
        }
      }
      const handlerSelectAll = (selection) => {
        formData.img_list = []
        formData.video_list = []
        formData.data_list = []
        if (selection.length > 0) {
          selection.forEach(item => {
            const selectedIndex = formData.checked_list.findIndex(selected => selected.sourceid == item.fid && selected.checked == true)
            if (selectedIndex == -1) {
              if (item.filetype == 2) {
                const index = formData.img_list.findIndex(d => d.fid == item.fid)
                if (index == -1) {
                  formData.img_list.push(item)
                }
              } else {
                const index = formData.video_list.findIndex(d => d.fid == item.fid)
                if (index == -1) {
                  formData.video_list.push(item)
                }
              }
            }
          })
        }
      }
      const handleConfirm = () => {
        if (sourceFiletype.value == 'image') {
          transferImage()
          if (formData.data_list.length <= 0) {
            ElMessage({type: 'warning', message: '请选择要导入的数据', duration: 2000})
          }
          exportStorageImage({data_list: formData.data_list}).then(response => {
            if (response.errcode == 0) {
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              resetFormData()
              cancelFolderDialog()
              context.emit('getDataList')
            } else {
              ElMessage({type: 'error', message: response.msg, duration: 2000})
            }
          })
        } else {
          transferVideo()
          if (formData.data_list.length <= 0) {
            ElMessage({type: 'warning', message: '请选择要导入的数据', duration: 2000})
          }
          exportStorageVideo({data_list: formData.data_list}).then(response => {
            if (response.errcode == 0) {
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              resetFormData()
              cancelFolderDialog()
              context.emit('getDataList')
            } else {
              ElMessage({type: 'error', message: response.msg, duration: 2000})
            }
          })
        }
      }
      const resetSourceData = () => {
        tableData.dataList = rootFolderDataList.value
        breadcrumbList.value = [
          {
            pid: 0,
            path: '/',
            name: '根目录'
          }
        ]
      }
      const transferImage = () => {
        formData.data_list = []
        formData.img_list.forEach(image => {
          let resolvepowerArr = image.resolvepower.split('*')
          let width = resolvepowerArr[0] ? parseInt(resolvepowerArr[0]) : 0
          let height = resolvepowerArr[1] ? parseInt(resolvepowerArr[1]) : 0
          let layout = 'unknown'
          if (width > 0 && height > 0) {
            if (width > height) {
              layout = 'horizontal'
            } else if (width < height) {
              layout = 'vertical'
            } else {
              layout = 'square'
            }
          }
          formData.data_list.push({
            groupid: parseInt(formData.groupid),
            name: image.name,
            extends: {
              width: width,
              height: height,
              size: parseInt(image.fsize)
            },
            sourceid: image.fid,
            layout: layout,
            mimetype: mimeTypeList[image.mimeid]
          })
        })
      }
      const transferVideo = () => {
        formData.data_list = []
        formData.video_list.forEach(video => {
          let resolvepowerArr = video.resolvepower.split('*')
          let width = resolvepowerArr[0] ? parseInt(resolvepowerArr[0]) : 0
          let height = resolvepowerArr[1] ? parseInt(resolvepowerArr[1]) : 0
          let layout = 'unknown'
          if (width > 0 && height > 0) {
            if (width > height) {
              layout = 'horizontal'
            } else if (width < height) {
              layout = 'vertical'
            } else {
              layout = 'square'
            }
          }
          formData.data_list.push({
            groupid: parseInt(formData.groupid),
            name: video.name,
            extends: {
              width: width,
              height: height,
              size: parseInt(video.fsize),
              duration: video.codetime ? parseInt(video.codetime) : 0
            },
            sourceid: video.fid,
            layout: layout,
            mimetype: mimeTypeList[video.mimeid] ? mimeTypeList[video.mimeid] : '',
          })
        })
      }
      const handleVideoPlay = (row) => {
        context.emit('handleVideoPlay', row)
      }
      /** 文件上传成功 **/
      const handleUploadSuccess = (response) => {
        if (response.errcode == 0) {
          ElMessage({type: 'success', message: response.msg, duration: 2000})
          getDataList()
        } else {
          ElMessage({type: 'error', message: response.msg, duration: 2000})
        }
      }
      /** 文件上传失败 **/
      const handleUploadError = (err) => {
        ElMessage({type: 'error', message: err, duration: 2000})
      }
      /** 开启文件上传弹框 **/
      /*const handleUploadFile = () => {
        if (sourceFiletype.value == 'image') {
          dialogUploadTitle.value = '上传图片文件'
        } else {
          dialogUploadTitle.value = '上传视频文件'
        }
        dialogUploadPath.value = getBreadcrumbPath()
        dialogUploadVisible.value = true
        nextTick(() => {
          uploadFileRef.value.uploadFormData.fileList = []
        })
      }*/
      /** 关闭上传文件弹框 **/
      const handleCancelUploadDialog = () => {
        dialogUploadVisible.value = false
      }

      const audioTableColumnRef = ref([])
      const handleAudioPlay = (refKey) => {
        Object.keys(audioTableColumnRef.value).forEach(fid => {
          if (refKey != fid) {
            audioTableColumnRef.value[fid].audioPause()
          }
        })
      }

      return {
        breadcrumbList,
        rootFolderDataList,
        tableData,
        isloading,
        handlerLink,
        isRoot,
        srcList,
        getStorageImageUrl,
        selectable,
        getDataList,
        queryList,
        cancelFolderDialog,
        formData,
        handlerSelect,
        handlerSelectAll,
        formatSize,
        handleConfirm,
        folderTableRef,
        sourceFiletype,
        handleVideoPlay,
        initialIndex,
        handleClickRowSelect,
        uploadAction,
        uploadFormData,
        handleUploadError,
        handleUploadSuccess,
        dialogUploadPath,
        dialogUploadTitle,
        dialogUploadVisible,
        // handleUploadFile,
        uploadFileRef,
        handleCancelUploadDialog,
        audioTableColumnRef,
        handleAudioPlay
      }
    }
  }
</script>

<style scoped lang="scss">

</style>
